package com.lambkit.spring.mvc;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.lambkit.core.AppContext;
import com.lambkit.spring.SpringLambkit;
import com.lambkit.spring.handler.LambkitHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangyong(孤竹行)
 */
@Configuration
public class LambkitWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // FastJson configuration
        configFastJson(converters);
        StaticLog.info("The FastJson configuration completed.");
    }

    /**
     * 拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //接口打印
        registry.addInterceptor(new LambkitHandlerInterceptor());
    }

    /**
     * 静态资源配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/**")
//                .addResourceLocations("classpath:/static/")
//                .addResourceLocations("classpath:/public/");
//        StaticLog.info("resource path 1.{} 2.{}", "classpath:/static/", "classpath:/public/");
        ResourceHandlerRegistration resourceHandlerRegistration = registry.addResourceHandler("/**");
        AppContext appContext = SpringLambkit.getApp().context();
        List<String> resourcePathList = appContext.resourceService().getWebResourcePathList(appContext.getResourcePath(), appContext.getResourcePathType());
        int i=1;
        for (String resourcePath : resourcePathList) {
            if(StrUtil.isBlank(resourcePath)) {
                continue;
            }
            if(!resourcePath.startsWith("classpath:") && !resourcePath.startsWith("file:")) {
                resourcePath = "file:" + resourcePath;
                if (!resourcePath.endsWith("/")) {
                    resourcePath = resourcePath + "/";
                }
            }
            resourceHandlerRegistration.addResourceLocations(resourcePath);
            StaticLog.info("resource path {}.{}", i, resourcePath);
            i++;
        }
    }

    /**
     * 跨域
     */
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                // 这里跨域最好配置域名
//                .allowedOrigins("*")
//                .maxAge(3600)
//                .allowCredentials(true)
//                .allowedMethods("GET", "POST", "OPTIONS", "DELETE", "PUT", "HEAD");
//    }

    public void configFastJson(List<HttpMessageConverter<?>> converters) {
        //StaticLog.info("-------------------------------SpringFastJsonConfig--------------------------------");
        // FastJson configuration
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.QuoteFieldNames,
                SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect);
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        // 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
}
